import { createRouter, createWebHashHistory } from 'vue-router'
import home from '@/router/index/home'
import login from '@/router/login/login'
import storage from '@/utils/common/storage'

const routes = [
  ...home,
  ...login
]

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  // 路由是否需要认证，不需要则直接跳转
  if (to.meta.requiredAuth === true) {
    // 获取用户登录成功后存储的登录标志
    const user = storage.get('user')
    if (!user) {
      // 没有登录则跳转至登陆页
      next({ path: '/login' })
      return
    }
    next()
  } else {
    // 如果已登录，重定向到首页
    if (to.path === '/login' && storage.get('user')) {
      next({ path: '/' })
    } else {
      setTimeout(100)
      next(true)
    }
  }
})

export default router
